

/**
 This file defined a x1client object for x1 tool client x1client
 which the native could use.
 
	XOneInfo:{
		  "appDisplayName": "",
		  "appName": "XOne",
		  "appVer": "4.0.1",
		  "appOSModule": "iPhone",
		  "phoneModule": "iPhone5",
		  "osVer": "7.0",
		  "protocolVer": "1.0.0",
		  "deviceId": "",
		  "bundleId": "com.netease.xone.hearthstone",
		  "channel": "appstore"
	}
*/ 
(function(window, $, undefined){

    var __ANDROID__   = (window['xOne']!=undefined);

    var x1client = {
        __DIRECTION__ : null,
        __COOKIE__ : null,
        __CONTEXT__   : null
    };

    x1client.history = {

        callbacks:{
            'back':[]
        },

        on:function(event, fn){
            if(x1client.history.callbacks[event]){
                x1client.history.callbacks[event].push(fn);
            }
        },

        trigger:function(event){

        },

        back:function(){
            //close the window if it's home page.
            if(/\/(.*html)?(#display\/index)?$/.test(window.location.href)){
                x1client.closeWindow();
            }
            //go back defaultly.
            else{
                window.history.back();
            }
        }
    };



    x1client.global = {

        data:null,
        appData:null,
        setInfoCallBack: null,
        getAppInfoCallBack: null,

        /**
         * 取得设备信息,Android callback function
         * @param data
         */
        setInfo:function(data){
            //x1client.global.data = data;
            x1client.global.data = JSON.parse(data);
            if(x1client.global.setInfoCallback){
                x1client.global.setInfoCallback(x1client.global.data);
            }
        },
        /**
         * 取得设备信息，通用接口
         * @param callback
         */
        getXOneInfo:function(callback){

            if(__ANDROID__){
                x1client.global.setInfoCallback = callback;
                window.xOne.getXOneInfo();
            }
            //for iOS.
            else{
                x1bridge.exec("getXOneInfo",""
                    ,function(result) {
                        x1client.global.data = JSON.parse(result);
                        callback(x1client.global.data);
                    }
                    ,function(error){

                    });
            }
        },
        /**
         * 获取APP安装信息，Android callback function
         * @param data
         */
        setAppInfo:function(data){
            x1client.global.appData=JSON.parse(data);
            if(x1client.global.getAppInfoCallBack){
                x1client.global.getAppInfoCallBack(x1client.global.appData);
            }
        },
        /**
         * 获取APP安装信息，通用接口
         * @param schemeList=[{
         *      id:自定义ID
         *      appid:app scheme
         * },...]
         * @param callback
         */
        getAppInfo:function(schemeList,callback){
            var parm={"list":schemeList};

            if(__ANDROID__){
                x1client.global.getAppInfoCallBack =callback;
                window.xOne.getAppInfo(JSON.stringify(parm));
            }
            //for iOS
            else{
                x1bridge.exec('getAppInfo',JSON.stringify(parm),
                    function(result){
                        x1client.global.appData = JSON.parse(result);
                        callback(x1client.global.appData);
                    });
            }
        }
    };


    x1client.account = {

        info:false,

        loginSuccessOnNative:function(info){
            //log(info);
            x1client.account.info = JSON.parse(info);
            x1client.__COOKIE__ = x1client.account.info.cookie.replace(/'/g,'');
            x1client.setCookie('session','"'+x1client.getCookie('session')+'"','Session','/');
            x1client.account.onLoginSuccess(x1client.account.info);
        },

        onLoginSuccess: null,

        /**
         * function x1client.account.getAuthInfo
         * @param options={
         *     success:成功回调
         *     error: 失败回调
         * }
         */
        getAuthInfo: function(options){
            if(__ANDROID__){
                x1client.account.onLoginSuccess = options.success;
                window.xOne.getAuthInfo();
            }
            //for iOS
            else{
                x1bridge.exec("getAuthInfo", "", function(info){
                    if('success' in options){
                        x1client.account.info = JSON.parse(info);
                        x1client.__COOKIE__ = x1client.account.info.cookie.replace(/"/g,'');
                        x1client.setCookie('session','"'+x1client.getCookie('session')+'"','Session','/');
                        options.success(x1client.account.info);
                    }
                }, function(error){
                    if('error' in options){
                        options.error(error);
                    }
                });
            }
        },
        /**
         * function startLogin
         * @param options={
         *     success:成功回调
         *     error: 失败回调
         * }
         */

        startLogin: function(options){
            //log('call native startLogin');
            if(__ANDROID__){
                x1client.account.onLoginSuccess = options.success;
                window.xOne.startLogin();
            }
            //for iOS
            else{
                x1bridge.exec('startLogin','',function(result){
                    options.success(JSON.parse(result));
                }, function(error){
                    options.error(error);
                });
            }
        }

    };

    x1client.navigate = function(section, params){
        x1client.__DIRECTION__ = {
            'section': section,
            'params': params
        };
    };

    /**
     * 关闭webView
     */
    x1client.closeWindow = function(){
        //for android
        if(__ANDROID__){
            window.xOne.closeWebView();
        }
        //for iOS
        else{
            x1bridge.exec('closeWebView');
        }
    };

    /**
     * 切换到native页面
     * @param id
     * @param type
     */
    x1client.toView=function(id,type){
        //for android
        var arg;
        if(type=="videoPlay"){
            arg='{"to":"'+type+'","url":"'+id+'"}';
        }else if(type=="atDetail"){
            arg='{"to":"'+type+'","name":"'+id+'"}';
        }else{
            arg='{"to":"'+type+'","id":"'+id+'"}';
        }

        if(__ANDROID__){
            window.xOne.toView(
                arg
            )}
        //for iOS
        else{
            x1bridge.exec("toView",
                arg,
                function(){alert("success")},
                function(){alert("fail")});
        }
    };
    /**
     * 打开本地app
     * @param appid
     */
    x1client.openApp=function(appid){
        if(__ANDROID__){
            //for Android
            window.xOne.launchPackage(appid);
        }else{
            //for ios
            window.location.href=appid+"://";
        }
    };
    /**
     function request
     @params context, options
     options = {
		needAuth:
		data:
		url:
		success:
		error:
		complete:
		method:
	 }
     */
    x1client.request = function(options){

        $.ajax($.extend({
                'dataType':'json',
                'complete':function(xhr, status){
                    //log('[request] '+status);
                    log('[reponse] '+xhr.responseText);
                },
                'error':function(xhr, type, error){
                    //log('[error] '+ error);
                },
                'headers': x1client.createRequestHeader(x1client.global.data, options.needAuth)
            },
            options, {
                'success':function(res){
                    if(0==res.resCode && 'success' in options){
                        options.success(res.data || []);
                    }
                    //if there is an error.
                    if(0!=res.resCode && 'error' in options){
                        options.error(res);
                    }
                }
            }));
    };

    /**
     function createRequestHeader
     @params context, needAuth
     context = {
		appVersion/appVer:
		appOSModule:
		osVer:
		phoneModule:
		channel:
		protocolVer:
	 }
     needAuth: true/false
     */
    x1client.createRequestHeader = function(context, needAuth){
        var headers = {
            "X-User-Agent":'XOne/'+(context['appVersion']? context.appVersion : context.appVer)+' ('+context.appOSModule+'; '
                +context.osVer+'; '+context.phoneModule+'; '
                +context.channel+'; 6EEE3E8A90D800CB1FD7820A2A0A753F7) '
                +context.protocolVer,
            "Cookie": (needAuth? x1client.__COOKIE__ : '')
        };
        if(x1client.getCookie('X-AntiCsrf')!=''){
            headers["X-AntiCsrf"] = x1client.getCookie('X-AntiCsrf');
        }
        return headers;
    };

    x1client.getCookie = function(key){
        var result = x1client.__COOKIE__.match(new RegExp(key+'=["\']?([^;"\']+)["\']?'));
        return (result? result[1] : '');
    };
    x1client.setCookie=function ( name, value, expires, path, domain, secure){
        var today = new Date();
        today.setTime( today.getTime() );
        if(expires){expires = expires * 1000 * 60 * 60;}
        var expires_date = new Date( today.getTime() + (expires) );
        document.cookie = name + "=" +value +
            ( ( expires ) ? ";expires=" + expires_date.toGMTString(): "" ) +
            ( ( path ) ? ";path=" + path : "" ) +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ( ( secure ) ? ";secure" : "" );
    };

    x1client.run = function(fn){
        if(__ANDROID__){
            window.setTimeout(function(){
                x1client.global.getXOneInfo(fn);
            }, 0);
        }
        else{
            x1bridge.addConstructor(function(){
                x1client.global.getXOneInfo(fn);
            });
        }
    };
    //bind to global namespace.
    if(!window.x1client){
        window.x1client = x1client;
    }

})(window, Zepto||jQuery);